<?php
interface DB{
	public function error_msg();
	public function connect();
	public function insert_id();
	public function sql_query($SQLScript);
	public function sql_list($SQLScript);
}
class MySQLDB implements DB{
	private $config=array();
	private $dbh;
	public function __construct($_host,$_id,$_pwd,$_dbname){
		$this->config['host'] = $_host;
		$this->config['id'] = $_id;
		$this->config['pwd'] = $_pwd;
		$this->config['db_name'] = $_db_name;
		if (empty($this->dbh))
			$this->connect();
	}
	public function connect(){
		list($host,$id,$pwd,$db_name) = array_values($this->config);
		$this->dbh = new mysqli($host,$id,$pwd,$db_name) or die('Can not connect db.');
	}
	public function  error_msg(){
		return $this->dbh->error;
	}
	public function insert_id(){
		return $this->dbh->insert_id;
	}
	public function sql_query($SQLScript){
		return $this->dbh->query($SQLScript);
	}
	public function sql_list($SQLScript){
		$result = $this->sql_query($SQLScript);
		$rows = array();
		if (!empty($result)){
			while ($row = $result->fetch_array(MYSQLI_ASSOC))
				$rows[] = $row;
		}
		$result->close();
		return $rows;
	}
}
class SQLite3DB implements DB{
	private $db_name;
	private $dbh;
	public function __construct($_db_name){
		$this->db_name=$_db_name;
		$this->connect();
	}
	public function __destruct(){
	}
	public function error_msg(){
		return $this->dbh->lastErrorMsg();
	}
	public function connect(){
		if (empty($this->dbh))
		$this->dbh= new SQLite3($this->db_name) or die('Can not connect DB.');
		return $this->dbh;
	}
	public function insert_id(){
		return $this->dbh->lastInsertRowId();
	}
	public function sql_prepare($SQLScript){
		return $this->dbh->prepare($SQLScript);
	}

	public function sql_query($SQLScript){
		try{
			if (strtolower(substr(rtrim($SQLScript),0,6)) === 'select')
			$result = $this->dbh->query($SQLScript);
			else
			$result = $this->dbh->exec($SQLScript);
		}catch (Exception $e){
			return null;
		}
		return $result;
	}
	public function sql_list($SQLScript){
		$result=$this->sql_query($SQLScript);
		$rows= array();
		if (!empty($result)){
			while ($row=$result->fetchArray(SQLITE3_ASSOC))
			$rows[]=$row;
		}
		return $rows;
	}
}
$db = new SQLite3DB(dirname(__FILE__).'/ndtl.db');
?>